﻿using ggHD.WebSite.MailService;
using OpenPop.Mime;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Net.Mime;


namespace ggHD.WebSite.Models
{   
    public class MailDetailViewModel
    {        
        public long Id { get; set; }
        public string HtmlVersion { get; set; }
        public string PlainTextVersion { get; set; }
        public string[] Attachments { get; set; }

        public static MailDetailViewModel CreateFromRawMail(RawMail rawMail)
        {
            var res = new MailDetailViewModel();
            
            var message = new Message(rawMail.RawData);
            res.Id = rawMail.Id;
            
            foreach (var textVer in message.FindAllTextVersions())
            {
                if (textVer.ContentType.MediaType == MediaTypeNames.Text.Html)
                    res.HtmlVersion = textVer.GetBodyAsText();

                if (textVer.ContentType.MediaType == MediaTypeNames.Text.Plain)
                    res.PlainTextVersion = textVer.GetBodyAsText();
            }

            var attList = new List<string>();
            foreach (var att in message.FindAllAttachments())            
                attList.Add(att.FileName);

            res.Attachments = attList.ToArray();

            return res;
        }
    }
}